import Taro from '@tarojs/taro';
import React, { useState, useEffect } from 'react';
import { View, Text, Image, ScrollView, Input } from '@tarojs/components';
import { MaterialIcons } from 'taro-icons';
import './index.scss';

// 客户类型定义
export interface Client {
  id: number;
  name: string;
  avatar: string;
  phone: string;
  source: string;
  contactTime: string;
  status: 'new' | 'contacted' | 'potential' | 'converted' | 'lost';
  lastContact: string;
  notes: string;
}

const ClientManagementPage: React.FC = () => {
  const [clients, setClients] = useState<Client[]>([]);
  const [filteredClients, setFilteredClients] = useState<Client[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchText, setSearchText] = useState('');
  const [activeTab, setActiveTab] = useState<string>('all');

  useEffect(() => {
    // 设置页面标题
    Taro.setNavigationBarTitle({ title: '客资管理' });
    // 加载客户数据
    loadClientData();
  }, []);

  useEffect(() => {
    // 根据搜索文本和标签筛选客户
    filterClients();
  }, [clients, searchText, activeTab]);

  const loadClientData = async () => {
    try {
      setIsLoading(true);
      // 模拟API调用
      // const response = await getClientListApi();
      
      // 模拟数据
      const mockClients: Client[] = [
        {
          id: 1,
          name: '张先生',
          avatar: 'https://via.placeholder.com/80',
          phone: '138****1234',
          source: '线上咨询',
          contactTime: '2024-01-15 10:30',
          status: 'new',
          lastContact: '尚未联系',
          notes: '想了解C1驾照培训课程'
        },
        {
          id: 2,
          name: '李女士',
          avatar: 'https://via.placeholder.com/80',
          phone: '139****5678',
          source: '朋友推荐',
          contactTime: '2024-01-14 15:20',
          status: 'contacted',
          lastContact: '2024-01-14 16:00',
          notes: '对C2自动挡课程感兴趣'
        },
        {
          id: 3,
          name: '王先生',
          avatar: 'https://via.placeholder.com/80',
          phone: '137****9012',
          source: '线下门店',
          contactTime: '2024-01-13 09:15',
          status: 'potential',
          lastContact: '2024-01-14 11:30',
          notes: '计划近期报名，需要详细了解价格'
        },
        {
          id: 4,
          name: '赵女士',
          avatar: 'https://via.placeholder.com/80',
          phone: '136****3456',
          source: '线上咨询',
          contactTime: '2024-01-10 14:45',
          status: 'converted',
          lastContact: '2024-01-12 10:00',
          notes: '已报名C1课程'
        },
        {
          id: 5,
          name: '钱先生',
          avatar: 'https://via.placeholder.com/80',
          phone: '135****7890',
          source: '广告推广',
          contactTime: '2024-01-09 11:20',
          status: 'lost',
          lastContact: '2024-01-10 09:30',
          notes: '价格太高，已选择其他驾校'
        }
      ];
      
      setClients(mockClients);
    } catch (error) {
      console.error('加载客户列表失败:', error);
      Taro.showToast({
        title: '数据加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const filterClients = () => {
    let result = [...clients];
    
    // 根据状态筛选
    if (activeTab !== 'all') {
      result = result.filter(client => client.status === activeTab);
    }
    
    // 根据搜索文本筛选
    if (searchText) {
      const searchLower = searchText.toLowerCase();
      result = result.filter(client => 
        client.name.toLowerCase().includes(searchLower) || 
        client.phone.includes(searchText) ||
        client.notes.toLowerCase().includes(searchLower)
      );
    }
    
    setFilteredClients(result);
  };

  const handleClientDetail = (clientId: number) => {
    // 跳转到客户详情页面
    Taro.navigateTo({
      url: `/pages/client-detail/index?id=${clientId}`
    });
  };

  const handleContactClient = async (clientId: number, clientPhone: string) => {
    // 调用拨打电话功能
    Taro.makePhoneCall({
      phoneNumber: clientPhone.replace(/\*+/g, '1234'),
      success: async () => {
        // 更新客户状态为已联系
        const updatedClients = clients.map(client => 
          client.id === clientId 
            ? { 
                ...client, 
                status: 'contacted', 
                lastContact: new Date().toLocaleString('zh-CN') 
              }
            : client
        );
        setClients(updatedClients);
        
        // 模拟更新状态到服务器
        // await updateClientStatusApi(clientId, 'contacted');
      }
    });
  };

  const getStatusText = (status: string) => {
    const statusMap: { [key: string]: string } = {
      'new': '新客资',
      'contacted': '已联系',
      'potential': '潜在客户',
      'converted': '已转化',
      'lost': '已流失'
    };
    return statusMap[status] || status;
  };

  const getStatusColor = (status: string) => {
    const colorMap: { [key: string]: string } = {
      'new': '#ff4d4f',
      'contacted': '#1890ff',
      'potential': '#faad14',
      'converted': '#52c41a',
      'lost': '#8c8c8c'
    };
    return colorMap[status] || '#666';
  };

  return (
    <View className="client-management-page">
      {/* 搜索栏 */}
      <View className="search-container">
        <View className="search-bar">
          <MaterialIcons name="search" size={28} color="#999" />
          <Input
            className="search-input"
            placeholder="搜索客户姓名、电话或备注"
            value={searchText}
            onChange={(e) => setSearchText(e.detail.value)}
          />
          {searchText && (
            <MaterialIcons 
              name="clear"
              size={24}
              color="#999"
              onClick={() => setSearchText('')}
            />
          )}
        </View>
      </View>

      {/* 状态标签栏 */}
      <ScrollView 
        className="tab-scroll"
        scrollX
        showsHorizontalScrollIndicator={false}
      >
        <View className="tab-bar">
          <View 
            className={`tab ${activeTab === 'all' ? 'active' : ''}`}
            onTap={() => setActiveTab('all')}
          >
            <Text className="tab-text">全部</Text>
          </View>
          <View 
            className={`tab ${activeTab === 'new' ? 'active' : ''}`}
            onTap={() => setActiveTab('new')}
          >
            <Text className="tab-text">新客资</Text>
          </View>
          <View 
            className={`tab ${activeTab === 'contacted' ? 'active' : ''}`}
            onTap={() => setActiveTab('contacted')}
          >
            <Text className="tab-text">已联系</Text>
          </View>
          <View 
            className={`tab ${activeTab === 'potential' ? 'active' : ''}`}
            onTap={() => setActiveTab('potential')}
          >
            <Text className="tab-text">潜在客户</Text>
          </View>
          <View 
            className={`tab ${activeTab === 'converted' ? 'active' : ''}`}
            onTap={() => setActiveTab('converted')}
          >
            <Text className="tab-text">已转化</Text>
          </View>
          <View 
            className={`tab ${activeTab === 'lost' ? 'active' : ''}`}
            onTap={() => setActiveTab('lost')}
          >
            <Text className="tab-text">已流失</Text>
          </View>
        </View>
      </ScrollView>

      {/* 客户列表 */}
      {isLoading ? (
        <View className="loading-container">
          <Text>加载中...</Text>
        </View>
      ) : (
        <ScrollView className="client-scroll">
          {filteredClients.length > 0 ? (
            filteredClients.map(client => (
              <View key={client.id} className="client-item">
                <View className="client-info" onTap={() => handleClientDetail(client.id)}>
                  <Image 
                    className="client-avatar" 
                    src={client.avatar} 
                    mode="aspectFill"
                  />
                  <View className="client-details">
                    <View className="client-header">
                      <Text className="client-name">{client.name}</Text>
                      <View className="client-status"
                        style={{ backgroundColor: getStatusColor(client.status) }}
                      >
                        <Text className="status-text">{getStatusText(client.status)}</Text>
                      </View>
                    </View>
                    <Text className="client-phone">{client.phone}</Text>
                    <View className="client-meta">
                      <Text className="meta-item">来源：{client.source}</Text>
                      <Text className="meta-item">咨询时间：{client.contactTime}</Text>
                    </View>
                    <Text className="client-notes">{client.notes}</Text>
                    <Text className="last-contact">最后联系：{client.lastContact}</Text>
                  </View>
                </View>
                
                {client.status !== 'converted' && client.status !== 'lost' && (
                  <View 
                    className="contact-btn"
                    onTap={() => handleContactClient(client.id, client.phone)}
                  >
                    <MaterialIcons name="phone" size={24} color="#fff" />
                    <Text className="contact-btn-text">联系客户</Text>
                  </View>
                )}
              </View>
            ))
          ) : (
            <View className="empty-container">
              <MaterialIcons name="people-outline" size={80} color="#ccc" />
              <Text className="empty-text">暂无客户数据</Text>
            </View>
          )}
        </ScrollView>
      )}
    </View>
  );
};

export default ClientManagementPage;